import 'dart:io';

import 'package:fish_redux/fish_redux.dart';
import 'package:flutter_blue/flutter_blue.dart';
import 'package:kunlun_gas/PublicSource/utils/bluetooth_helper.dart';
// import 'package:flutter_blue_card_plugin/flutter_blue_card_plugin.dart'
//     as bleHelper;
import 'package:kunlun_gas/PublicSource/utils/xa_ble_manager/XaBleManager.dart';
import 'package:kunlun_gas/app_files.dart';
import 'package:permission/permission.dart';
import 'package:shared_preferences/shared_preferences.dart';
import 'dart:convert' as convert;
import 'action.dart';
import 'state.dart';

Effect<XABleSaveViewState> buildEffect() {
  return combineEffects(<Object, Effect<XABleSaveViewState>>{
    XABleSaveViewAction.onSubmit: _onSubmit,
    XABleSaveViewAction.onConnect: _onConnect,
    XABleSaveViewAction.onNetWork: _onNetWork,
    Lifecycle.initState: _initState,
  });
}

void _onNetWork(Action action, Context<XABleSaveViewState> ctx) async {
  if (ctx.state.cardContent == null) {
    CommonUtils.showAlertView(ctx.context, '请连接蓝牙卡');
    return;
  }
  XaBleManager xaBleManager = XaBleManager.instance;
  CommonUtils.showWaitLoading(ctx.context);
  XABleResponse ret = await xaBleManager.queryNetwork();
  Navigator.pop(ctx.context);
  if (ret != null) {
    CommonUtils.showToast(ctx.context, '设置成功');
  } else {
    CommonUtils.showErrorInfo(ctx.context, '设置失败');
  }
}

void _initState(Action action, Context<XABleSaveViewState> ctx) async {
  if (Platform.isAndroid) {
    FlutterBlue.instance.onPermission();
    // List<PermissionName> permissionNames = [];
    // permissionNames.add(PermissionName.BLE_CONNECT);
    // var permissions = await Permission.requestPermissions(permissionNames);
  }
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  final SharedPreferences prefs = await _prefs;
  String gas = prefs.getString('bleNo_${ctx.state.model.userID}') ?? '';
  ctx.state.numberController.text = gas;
  ctx.dispatch(XABleSaveViewActionCreator.onAction());
  ResultData res = await CommonNetWork.getCardMemo(ctx.state.model.userID);
  if (res.success) {
    ctx.state.cardMemo = res.data;
  } else {
    await CommonUtils.showAlertView(ctx.context, res.desc);
    Navigator.pop(ctx.context);
  }
}

void _onConnect(Action action, Context<XABleSaveViewState> ctx) async {
  if (ctx.state.numberController.text.isEmpty) {
    CommonUtils.showErrorInfo(ctx.context, '请输入蓝牙卡号');
    return;
  }
  Future<SharedPreferences> _prefs = SharedPreferences.getInstance();
  final SharedPreferences prefs = await _prefs;
  prefs.setString(
      'bleNo_${ctx.state.model.userID}', ctx.state.numberController.text);
  CommonUtils.closeKey(ctx.context);
  XaBleManager xaBleManager = XaBleManager.instance;
  CommonUtils.showWaitLoading(ctx.context, descText: '正在连接中');
  int ret = await xaBleManager.connect(ctx.state.numberController.text);
  Navigator.pop(ctx.context);
  if (ret == -1) {
    CommonUtils.showAlertView(ctx.context, '未找到蓝牙卡');
    return;
  }
  if (ret != 0) {
    CommonUtils.showAlertView(ctx.context, '连接情况: $ret');
    return;
  }
  ctx.state.uuid = '';
  ctx.state.cardContent = null;
  CommonUtils.showWaitLoading(ctx.context, descText: '读卡中...');
  XABleResponse uuidRes = await xaBleManager.getUUID();
  if (uuidRes == null) {
    Navigator.pop(ctx.context);
    CommonUtils.showAlertView(ctx.context, 'UUID 获取失败');
    return;
  }
  ctx.state.uuid = uuidRes.uuid;
  await Future.delayed(Duration(seconds: 3));
  Navigator.pop(ctx.context);

  bool authRes =
      await xaBleManager.autoRequestAuth(ctx.state.uuid, ctx.context);
  if (authRes != true) {
    return;
  }
  CommonUtils.showWaitLoading(ctx.context, descText: '读卡中');
  XABleResponse readContentData = await xaBleManager.readCiphertextData();
  if (readContentData == null) {
    Navigator.pop(ctx.context);
    CommonUtils.showAlertView(ctx.context, '读卡失败：cmd 03');
    return;
  }
  var readRes =
      await xaBleManager.decryptCardData(readContentData, ctx.state.uuid);
  if (!(readRes is XAServiceResponseModel)) {
    Navigator.pop(ctx.context);
    CommonUtils.showAlertView(ctx.context, '加密机连接错误: $readRes');
    return;
  }
  if (readRes.status != '00') {
    Navigator.pop(ctx.context);
    CommonUtils.showAlertView(ctx.context, '解密失败 ${readRes.status}');
    return;
  }
  Navigator.pop(ctx.context);
  ctx.state.cardContent = ReadCardContentModel.fromContent(readRes.data);
  CommonUtils.showToast(ctx.context, '已连接');


  ctx.dispatch(XABleSaveViewActionCreator.onAction());
}

void _onSubmit(Action action, Context<XABleSaveViewState> ctx) async {
  if (ctx.state.model.status != '1') return;
  if (ctx.state.cardContent == null) {
    CommonUtils.showAlertView(ctx.context, '请连接蓝牙卡');
    return;
  }
  // if ((double.tryParse(ctx.state.cardContent.cardGas) ?? 0.0) != 0.0) {
  //   CommonUtils.showAlertView(
  //       ctx.context, '卡中有剩余气量，请先上表: ${ctx.state.cardContent.cardGas}');
  //   return;
  // }
  // Map cardInfo = convert.jsonDecode(ctx.state.cardMemo);
  // if (int.tryParse(CommonUtils.checkNullToString(cardInfo['cardNo'])) !=
  //     int.tryParse(ctx.state.cardContent.cardNo)) {
  //   CommonUtils.showAlertView(
  //       ctx.context, '蓝牙卡不是该用户对应卡号: ${ctx.state.cardContent.cardNo}');
  //   return;
  // }
  // CommonUtils.showWaitLoading(ctx.context, descText: '写卡中');
  // try {
  //   WriteCardContentModel writeModel = WriteCardContentModel.cardModel(
  //     buyTime: 1,
  //     totalBuyGas: 1,
  //     buyGas: int.parse(
  //         double.tryParse(ctx.state.model.orderGas).toStringAsFixed(0)),
  //     readCardModel: ctx.state.cardContent,
  //   );
  //   XaBleManager xaBleManager = XaBleManager.instance;
  //   var readRes =
  //       await xaBleManager.encryptCardData(writeModel, ctx.state.uuid);
  //   if (!(readRes is XAServiceResponseModel)) {
  //     Navigator.pop(ctx.context);
  //     CommonUtils.showAlertView(ctx.context, '加密机连接错误: $readRes');
  //     return;
  //   }
  //   if (readRes.status != '00') {
  //     Navigator.pop(ctx.context);
  //     CommonUtils.showAlertView(ctx.context, '${readRes.toString()}');
  //     return;
  //   }
  //   XAServiceResponseModel res = readRes as XAServiceResponseModel;
  //   XABleResponse writeRes =
  //       await xaBleManager.writeCiphertextData(res.data + res.textEnd);
  //   if (writeRes != null) {
  //     XABleResponse ret = await xaBleManager.queryNetwork();
  //     if (ret != null) {
  //       double totalGas = double.tryParse(
  //               CommonUtils.checkNullToString(cardInfo['aggGas'])) ??
  //           0.0;
  //       totalGas += int.parse(
  //           double.tryParse(ctx.state.model.orderGas).toStringAsFixed(0));
  //       cardInfo['aggGas'] = totalGas;
  //       cardInfo['lastGas'] = int.parse(
  //           double.tryParse(ctx.state.model.orderGas).toStringAsFixed(0));
  //       bleHelper.ResultData statusRes =
  //           await BlueToothHelper.changeOrderStatus(
  //               '',
  //               ctx.state.model.accountNo,
  //               ctx.state.model.orderID,
  //               convert.jsonEncode(cardInfo));
  //       Navigator.pop(ctx.context);
  //       String desc = statusRes.success ? '圈存成功，请保持连接并立即上表' : '订单状态修改失败';
  //       await CommonUtils.showAlertView(ctx.context, desc);
  //       bus.emit('refreshOrderList');
  //       Navigator.pop(ctx.context);
  //       Navigator.pop(ctx.context);
  //       return;
  //     } else {
  //       Navigator.pop(ctx.context);
  //       CommonUtils.showAlertView(ctx.context, '设置上表模式失败');
  //       return;
  //     }
  //   } else {
  //     Navigator.pop(ctx.context);
  //     CommonUtils.showAlertView(ctx.context, '写卡失败：cmd 07');
  //     return;
  //   }
  // } catch (e) {
  //   Navigator.pop(ctx.context);
  //   CommonUtils.showAlertView(ctx.context, e);
  //   return;
  // }
}
